package com.aliyun.tiangong.security;

import com.aliyun.tiangong.constant.TiangongConstant;
import com.aliyun.tiangong.support.RestResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * @author xinghen
 * @ClassName: SecurityController
 * @Package: com.aliyun.tiangong.security
 * @Description 安全相关服务
 * @create 2018-04-20 15:01
 */
@Slf4j
@RestController
public class SecurityController {

    private RequestCache requestCache = new HttpSessionRequestCache();

    private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();

    @RequestMapping("/auth/require")
    public RestResult login(HttpServletRequest request, HttpServletResponse response) throws IOException {
        SavedRequest savedRequest = requestCache.getRequest(request, response);
        if (Objects.nonNull(savedRequest)) {
            String targetUrl = savedRequest.getRedirectUrl();
            if (!StringUtils.endsWith(targetUrl, TiangongConstant.JSON_URL_SUFFIX)) {
                redirectStrategy.sendRedirect(request, response, "/login");
            }
        }
        return RestResult.error(HttpStatus.UNAUTHORIZED.value(), "访问的服务需要身份认证");
    }

}
